package com.itzhigui.controller.api;

import com.itzhigui.bo.PaymentBo;
import com.itzhigui.entity.User;
import com.itzhigui.service.PayService;
import com.itzhigui.utils.ConstantUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 支付宝支付，控制器
 *
 * @Author: 张兴宇
 * @DateTime: 2023/11/16 11:19
 **/
@RestController
@Slf4j
@RequestMapping(value = "/api/pay")
public class ApiPayController {

    @Resource
    private PayService payService;

    /**
     * 下单支付
     *
     * @param bo
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/confirm", produces = {"text/html;charset=UTF-8"})
    public Object pay(
            PaymentBo bo, HttpSession session
    ) throws Exception {
        User loginUser = (User) session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        System.out.println(bo.getSubject() + " : " + bo.getTotal().toString());
        bo.setUserId(loginUser.getId()); //设置用户编号
        return payService.pay(bo);
    }

    //支付成功时的回调接口
    @PostMapping(value = "/notify")
    public void notify(HttpServletRequest request) {
        //从request中获取到所有支付宝成功后给我们返回所有支付信息
        Map<String, String[]> map = request.getParameterMap();
        map.forEach((k, v) -> {
            System.out.println("---------"+ k +"--------");
            //打印值
            for (int i = 0; i < v.length; i++) {
                System.out.println(v[i]);
            }
        });
        payService.updatePayStatus(map);
    }
}
